package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.R;
import com.itheima.reggie.contants.MessageConstant;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.ex.CustomerException;
import com.itheima.reggie.mapper.EmployeeMapper;
import com.itheima.reggie.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

/**
 * 员工业务层实现
 * @author ghy
 * @version v1.0
 * create on 2022/11/15 14:57
 */
@Service
@Slf4j
@Transactional
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements EmployeeService {
    @Override
    public R add(Employee employee, Long employeeId) {

        //1.判断员工用户名是否存在？
        //where username = ?
        LambdaQueryWrapper<Employee> lqw = Wrappers.<Employee>lambdaQuery();
        lqw.eq(Employee::getUsername, employee.getUsername());
        Employee emp = this.getOne(lqw);
        //1.1 存在，返回错误结果
        if(emp != null) {
            //抛出异常，程序中断
            throw new CustomerException(MessageConstant.EMPLOYEE_USERNAME_EXISTS);
            //throw new CustomerException(emp.getUsername() + "用户名已经存在");
            //return R.error(emp.getUsername() + "用户名已经存在");
        }
        //2.补全实体属性
        //密码、状态、创建时间、更新时间、创建人、更新人
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        employee.setStatus(1);

        //下面属性使用公共字段填充完成
        //employee.setCreateTime(LocalDateTime.now());
        //employee.setUpdateTime(LocalDateTime.now());
        //employee.setCreateUser(employeeId);
        //employee.setUpdateUser(employeeId);

        //3.保存
        this.save(employee);
        return R.success(MessageConstant.EMPLOYEE_ADD_SUCCESS);
    }

    @Override
    public R modify(Employee employee, Long employeeId) {
        if(StringUtils.isBlank(employee.getUsername())){
            //启用或禁用功能
            //employee.setUpdateTime(LocalDateTime.now());
            //employee.setUpdateUser(employeeId);
            this.updateById(employee);
        } else {
            //修改
            //1.判断当前用户名是否被使用，除开自己
            Employee dbEmp = this.getOne(Wrappers.<Employee>lambdaQuery().eq(Employee::getUsername,employee.getUsername()));
            if(dbEmp == null || dbEmp.getId().equals(employee.getId())) {
                //employee.setUpdateTime(LocalDateTime.now());
                //employee.setUpdateUser(employeeId);
                this.updateById(employee);
            } else {
                throw new CustomerException(MessageConstant.EMPLOYEE_USERNAME_EXISTS);
            }
        }

        return R.success("员工修改成功");
    }
}
